package com.tanhua.app.interceptor;

import com.tanhua.commons.utils.JwtUtils;
import com.tanhua.model.pojo.User;
import io.jsonwebtoken.Claims;
import org.springframework.http.HttpStatus;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class LoginInterceptor extends HandlerInterceptorAdapter {


    //执行登录校验
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1. 获取请求头中的token
        String token = request.getHeader("Authorization");

        //2.  校验token是否合法
        boolean verifyToken = JwtUtils.verifyToken(token);

        //如果不合法，校验失败，响应401，返回false 拦截请求
        if (!verifyToken) {
            //response.setStatus(401);
            response.setStatus(HttpStatus.UNAUTHORIZED.value());
            return false;
        }

        //3. 校验成功，解析token，获取当前登录的用户信息
        Claims claims = JwtUtils.getClaims(token);
        Long id = Long.parseLong(claims.get("id").toString());
        String mobile = claims.get("mobile").toString();

        User user = new User();
        user.setId(id);
        user.setMobile(mobile);

        //4. 把用户数据放到 ThreadLocal中
        UserHolder.setUser(user);

        //放行
        return true;
    }


    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //清理ThreadLocal数据
        UserHolder.remove();
    }
}
